package com.peng.online_chat_codec;

import com.peng.online_chat_codec.codec.MsgEncoder;
import com.peng.online_chat_codec.entity.Msg;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.TimeUnit;

public class ChatClient {

    private Channel currentClient;

    public void sendMsg(String msg) {
//        currentClient.writeAndFlush(msg);
        currentClient.writeAndFlush(new Msg(5, 5));

    }

    public void close() {
        if (currentClient != null) currentClient.close();
    }

    public void connectServer() {
        ChatFrame.INSTANCE.ta.setText("正在连接在线聊天室。。。。");
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        try {
            ChannelFuture channelFuture = b.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChanelInitHandler(this))
                    .connect("localhost", 8888)
                    .addListener((ChannelFutureListener) future -> {
                        ChatFrame.INSTANCE.ta.setText("");
                        if (!future.isSuccess()) {
                            ChatFrame.INSTANCE.ta.setText("服务器连接失败。。。。5秒后程序即将退出\n");
                            TimeUnit.SECONDS.sleep(5);
                            System.exit(-1);
                            return;
                        }
                        ChatFrame.INSTANCE.ta.setText("服务器连接成功。。。\n");
                        ChatFrame.INSTANCE.tf.setEditable(true);
                    }).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    private static class ChanelInitHandler extends ChannelInitializer<NioSocketChannel> {
        ChatClient chatClient;

        public ChanelInitHandler(ChatClient chatClient) {
            this.chatClient = chatClient;
        }

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(new MsgEncoder())
                    .addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            chatClient.currentClient = ctx.channel();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            System.out.println("222");
                            ByteBuf byteBuf = null;
                            try {
                                byteBuf = (ByteBuf) msg;
                                String s = byteBuf.toString(CharsetUtil.UTF_8);
                                ChatFrame.INSTANCE.ta.setText(ChatFrame.INSTANCE.ta.getText() + s + "\n");
                            } finally {
                                ReferenceCountUtil.release(byteBuf);
                            }
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            cause.printStackTrace();
                        }
                    });
        }
    }
}
